package com.sx.core.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang.ObjectUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;

import javax.servlet.http.HttpServletRequest;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by lihao on 16/4/11.
 */
public class WxJsUtils {
    static HttpClientInstance httpClientInstance=HttpClientInstance.getInstance();
    static private Log log= LogFactory.getLog(WxJsUtils.class);
    public WxJsUtils() {
    }
//    获取openID
    public static Map getUserInfo(String appId,String appSecret,String code,boolean header){
        String openIdUrl = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=%s&secret=%s&code=%s&grant_type=authorization_code";
        Map ret = new HashMap();
        String result = String.format(openIdUrl, appId, appSecret, code);
        String res=httpClientInstance.get(result);
        log.debug("getUserInfo---"+res);
        if(res!=null){
            JSONObject jsonObject= JSON.parseObject(res);
            ret.putAll(jsonObject);
        }
        if(ret.isEmpty() || ret.get("openid")==null){
            return null;
        }
        if(header){
            String infoUrl="https://api.weixin.qq.com/sns/userinfo?access_token=%s&openid=%s&lang=zh_CN";
            infoUrl=String.format(infoUrl,ret.get("access_token"),ret.get("openid"));
            res=httpClientInstance.get(infoUrl);

            if(res!=null){
                JSONObject jsonObject= JSON.parseObject(res);
                ret.putAll(jsonObject);
            }
            if(ret.isEmpty() || ret.get("openid")==null){
                return null;
            }
        }
        return ret;
    }

    /**获取基础token
     * 请登录“微信公众平台-开发-基本配置”提前将服务器IP地址添加到IP白名单中，点击查看设置方法，否则将无法调用成功。
     * {"access_token":"11_Rvzi94Xipe0QVVHE0TFKiYblwAv6fjJ6FgEkRP5jSMpf-Uwm283AQQxfg247TdEVG_4pXoN3cLecOk43PVhYKKAOvpj15E_i5loRuornUsu6SL7aPX4wTYVo3tVvo6z6Ic9kjfvt6lGCmDBXGPKiAFABKF","expires_in":7200}

     * @param appid
     * @param secret
     * @return
     */
    public static JSONObject getBaseToken(String appid, String secret){
        String url="https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s";
        url=String.format(url,appid,secret);
        String result = httpClientInstance.get(url);
        if(StringUtils.isEmpty(result)){
            return null;
        }
        log.debug("getBaseToken---->>>"+result);
        JSONObject ret= JSON.parseObject(result);
        return ret;
    }
    /**创建自定义菜单
     * {
     "button":[
     {
     "type":"click",
     "name":"今日歌曲",
     "key":"V1001_TODAY_MUSIC"
     },
     {
     "name":"菜单",
     "sub_button":[
     {
     "type":"view",
     "name":"搜索",
     "url":"http://www.soso.com/"
     },
     {
     "type":"miniprogram",
     "name":"wxa",
     "url":"http://mp.weixin.qq.com",
     "appid":"wx286b93c14bbf93aa",
     "pagepath":"pages/lunar/index"
     },
     {
     "type":"click",
     "name":"赞一下我们",
     "key":"V1001_GOOD"
     }]
     }]
     }
     * @return
     */
    public static boolean createMenu(String token,Map buttons){
        String url=" https://api.weixin.qq.com/cgi-bin/menu/create?access_token=%s";
        url=String.format(url,token);
        String result = httpClientInstance.postJson(url,buttons);
        if(StringUtils.isEmpty(result)){
            return false;
        }
        log.debug("createMenu---->>>"+result);
        JSONObject ret= JSON.parseObject(result);
        return StringUtils.equals(ret.getString("errcode"),"0") && StringUtils.equals(ret.getString("errmsg"),"ok");
    }



    /**获取用户列表
     * @return
     */
    public JSONObject getUsers(String access_token){
        String url="https://api.weixin.qq.com/cgi-bin/user/get?access_token=%s&next_openid=";
        url=String.format(url,access_token);
        String result = httpClientInstance.get(url);
        if(StringUtils.isEmpty(result)){
            return null;
        }
        log.debug("getUsers---->>>"+result);
        JSONObject ret= JSON.parseObject(result);
        return ret;
    }
     /**获取用户详细信息
     * @return
     */
    public JSONObject getUserDetail(String access_token, String openid){
        String url="https://api.weixin.qq.com/cgi-bin/user/info?access_token=%s&openid=%s&lang=zh_CN";
        url=String.format(url,access_token,openid);
        String result = httpClientInstance.get(url);
        if(StringUtils.isEmpty(result)){
            return null;
        }
        log.debug("getUsers---->>>"+result);
        JSONObject ret= JSON.parseObject(result);
        return ret;
    }
     /**群发发送消息
     * @return
     */
    public JSONObject sendMessage(String access_token, String content, String... openids){
        String url="https://api.weixin.qq.com/cgi-bin/message/mass/send?access_token=%s";
        url=String.format(url,access_token);
        /**
         * {
         "touser":[
         "OPENID1",
         "OPENID2"
         ],
         "msgtype": "text",
         "text": { "content": "hello from boxer."}
         }
         */
        Map map=new HashMap();
        List touser=new ArrayList();
        touser.addAll(Arrays.asList(openids));
        Map text=new HashMap();
        text.put("content",content);

        map.put("touser",touser);
        map.put("msgtype","text");
        map.put("text",text);

        String result = httpClientInstance.postJson(url,map);
        if(StringUtils.isEmpty(result)){
            return null;
        }
        log.debug("sendMessage---->>>"+result);
        JSONObject ret= JSON.parseObject(result);
        return ret;
    }
    /**客服发送消息
     * @return
     */
    public static JSONObject sendKfMessage(String access_token, String content, String openid){
        String url="https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=%s";
        url=String.format(url,access_token);

        Map map=new HashMap();
        Map text=new HashMap();
        text.put("content",content);

        map.put("touser",openid);
        map.put("msgtype","text");
        map.put("text",text);

        String result = httpClientInstance.postJson(url,map);
        if(StringUtils.isEmpty(result)){
            return null;
        }
        log.debug("sendMessage---->>>"+result);
        JSONObject ret= JSON.parseObject(result);
        return ret;
    }
    //获取微信对象
    public static WxCommand getCommand(HttpServletRequest request, String appId, String secret){
        String code = request.getParameter("code");
        log.debug("code is :" + code);
        WxCommand wxCommand = null;
        if(StringUtils.isEmpty(code)){
            return null;
        }
        Map map = getUserInfo(appId, secret, code, false);
        if (map != null) {
            String openid = ObjectUtils.toString(map.get("openid"));
            log.info("openid is>>>>"+openid);
            wxCommand = new WxCommand(openid,code);
//            CoreWebUtils.setSessionAttribute(request, "wx", wxCommand);
        }
        return wxCommand;
    }




    ////    获取js ticket
    public  static String getJsTicket(String token){
        String ticketUrl="https://api.weixin.qq.com/cgi-bin/ticket/getticket?type=jsapi&access_token=%s";
        ticketUrl=String.format(ticketUrl,token);
        String result = httpClientInstance.get(ticketUrl);
        if(StringUtils.isEmpty(result)){
            return null;
        }
        JSONObject ret= JSON.parseObject(result);
        return ret.getString("ticket");
    }
    /**
     * 获取js接口权限信息
     * @param appid
     * @param ticket
     * @param url  url（当前网页的URL，不包含#及其后面部分）
     * @return
     */
    public static Map getJsInfo(final String appid, String ticket, String url){
        final String timeStr = System.currentTimeMillis()+"";
        final String nonStr = WxPayUtils.nonStr();
        StringBuffer sb=new StringBuffer();
        sb.append("jsapi_ticket=").append(ticket).append("&");
        sb.append("noncestr=").append(nonStr).append("&");
        sb.append("timestamp=").append(timeStr).append("&");
        sb.append("url=").append(url);
        final String sign= Sha.sha(sb.toString());
        Map map=new HashMap();
        map.put("appId",appid);
        map.put("timestamp",timeStr);
        map.put("nonceStr",nonStr);
        map.put("signature",sign);
        return map;
    }
     /**
     * 获取临时素材--图片
      * @param token
     * @param media_id YI8pMKPgumaAHU6byRfCLDZj_syXkIueqNTYKKK7kfL1g54AQf2YhRKYiyn2eE9n
     * @return
     */
    public <T> T getPicSource(final String token, String media_id,HttpClientInstance.HttpStreamCallback callback){
        String url="https://api.weixin.qq.com/cgi-bin/media/get?access_token="+token+"&media_id="+media_id;
        return httpClientInstance.getStream(url,callback);
    }
    /**
     *
     * @param token
     * @param template
     * @return
     */
    public static JSONObject sendTemplateMsg(String token,Template template)
    {
        boolean flag=false;
        String requestUrl="https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=%s";
        requestUrl=String.format(requestUrl,token);
        String result = httpClientInstance.postJson(requestUrl,template);
        if(StringUtils.isEmpty(result)){
            return null;
        }
        log.debug("模板消息返回:"+result);
        JSONObject ret= JSON.parseObject(result);
        return ret;
    }
    static public class Template {

        // 消息接收方
        private String touser;
        // 模板id
        private String template_id;
        // 模板消息详情链接
        private String url;
        // 消息顶部的颜色
        private String topcolor;
        //
        private Map miniprogram;
        // 参数列表
        private Map<String,Object> data;

        public String getTouser() {
            return touser;
        }

        public void setTouser(String touser) {
            this.touser = touser;
        }

        public String getTemplate_id() {
            return template_id;
        }

        public void setTemplate_id(String template_id) {
            this.template_id = template_id;
        }

        public String getUrl() {
            return url;
        }

        public void setUrl(String url) {
            this.url = url;
        }


        public Map getMiniprogram() {
            return miniprogram;
        }

        public void setMiniprogram(Map miniprogram) {
            this.miniprogram = miniprogram;
        }

        public Map<String, Object> getData() {
            return data;
        }

        public void setData(Map<String, Object> data) {
            this.data = data;
        }

        public String getTopcolor() {
            return topcolor;
        }

        public void setTopcolor(String topcolor) {
            this.topcolor = topcolor;
        }
    }
    static public class TemplateParam {

        // 参数值
        private String value;
        // 颜色
        private String color;

        public TemplateParam(String name,String value,String color) {
            this.value=value;
            this.color=color;
        }

        public TemplateParam(String value, String color) {
            this.value=value;
            this.color=color;
        }


        public String getValue() {
            return value;
        }

        public void setValue(String value) {
            this.value = value;
        }

        public String getColor() {
            return color;
        }

        public void setColor(String color) {
            this.color = color;
        }
    }

    public static Element parseXml(String xml){
        if(xml==null){
            return null;
        }
        try {
            Document document = DocumentHelper.parseText(xml);
            Element element = document.getRootElement();
            return element;
        } catch (DocumentException e) {
        } catch (Exception e) {
        }
        return null;
    }
    static class WxMenu implements Serializable{
        private String type;
        private String name;
        private String key;
        private String url;
        private List<WxMenu> sub_button=new ArrayList<>();

        public String getType() {
            return type;
        }

        public WxMenu setType(String type) {
            this.type = type;
            return this;
        }

        public String getName() {
            return name;
        }

        public WxMenu setName(String name) {
            this.name = name;
            return this;
        }

        public String getKey() {
            return key;
        }

        public WxMenu setKey(String key) {
            this.key = key;
            return this;
        }

        public String getUrl() {
            return url;
        }

        public WxMenu setUrl(String url) {
            this.url = url;
            return this;
        }

        public List<WxMenu> getSub_button() {
            return sub_button;
        }

        public WxMenu setSub_button(List<WxMenu> sub_button) {
            this.sub_button = sub_button;
            return this;
        }
        public WxMenu addSub_button(WxMenu sub_button) {
            this.sub_button.add(sub_button);
            return this;
        }

    }

    public static Map createMenuMap(String url){
//        String url="http://test.vgirlfq.com";

//        WxMenu wxMenu1=new WxMenu().setName("保密时讯")
//                .addSub_button(new WxMenu().setName("工作时讯").setKey(Constants.M1_key_gzsx).setType("click"))
//                .addSub_button(new WxMenu().setName("警醒案例").setKey(Constants.M1_key_jxal).setType("click"))
//                .addSub_button(new WxMenu().setName("知识竞赛").setKey(Constants.M1_key_zsjs).setType("click"));
        WxMenu wxMenu2=new WxMenu().setName("工作台").setKey("key_gzt").setType("view").setUrl("http://v1.scnetview.com/wechat/msg/openid");
        WxMenu wxMenu3=new WxMenu().setName("更多").setKey("key_more").setType("view").setUrl("https://www.baidu.com");
//        WxMenu wxMenu3=new WxMenu().setName("工作交流")
//                .addSub_button(new WxMenu().setName("先进推介").setKey(Constants.M3_key_xjtj).setType("click"))
//                .addSub_button(new WxMenu().setName("产品推荐").setKey(Constants.M3_key_cptj).setType("click"))
//                .addSub_button(new WxMenu().setName("我要咨询").setKey(Constants.M3_key_refer).setType("click"));

        List list=new ArrayList();
//        list.add(wxMenu1);
        list.add(wxMenu2);
        list.add(wxMenu3);
        Map params=new HashMap();
        params.put("button",list);
        return params;
    }






    public static void main(String[] args) throws Exception{




        /**
         * 测试消息群发
         * 仁和公众号
         * appid:wx91f91fab19f660ad
         * appsecret：58adf7794404553b1187a305229abda3
         */

//        String appid="wx91f91fab19f660ad";
//        String appsecret="9791420dade9f51c51d50885d350f0f7";

        String appid="wx0eb932c0be6e1b91";
        String appsecret="19bc0e0f7e033298125742e23163873d";


        /**
         *
         {
         "button":[
         {
         "type":"click",
         "name":"今日歌曲",
         "key":"V1001_TODAY_MUSIC"
         },
         {
         "name":"菜单",
         "sub_button":[
         {
         "type":"view",
         "name":"搜索",
         "url":"http://www.soso.com/"
         },
         {
         "type":"miniprogram",
         "name":"wxa",
         "url":"http://mp.weixin.qq.com",
         "appid":"wx286b93c14bbf93aa",
         "pagepath":"pages/lunar/index"
         },
         {
         "type":"click",
         "name":"赞一下我们",
         "key":"V1001_GOOD"
         }]
         }]
         }
         */
        String url="http://bmj.cdpidu.org.cn";
        WxMenu wxMenu1=new WxMenu().setName("菜单1_1").setKey("menu_1_1").setType("click");
        WxMenu wxMenu2=new WxMenu().setName("菜单2")
                .addSub_button(new WxMenu().setName("菜单2_1").setKey("menu_2_1").setType("click"))
                .addSub_button(new WxMenu().setName("菜单2_2").setKey("menu_2_2").setType("click"))
                .addSub_button(new WxMenu().setName("菜单2_3").setKey("menu_2_3").setType("view").setUrl("http://test.vgirlfq.com"));
        List list=new ArrayList();
        list.add(wxMenu1);
        list.add(wxMenu2);
        Map params=new HashMap();
        params.put("button",list);
        JSONObject token_json=getBaseToken(appid,appsecret);
        String token=token_json.getString("access_token");
//        {"access_token":"12_jN1acAbXZbL8IjMUuS31wOGrstGANMWqy8oTOYhSPx02NX3H3p1Kc6EevKeSpEydWrlth1SAQEWb0Sk6IaUmGPATvLI_YcU_MtWGGz9sFBhwX9n4bTssM3YC8jfx_5WBPNC6K4vMOY0vnZqEXILbADAJUX","expires_in":7200}


//        String token="13_xps_pZW267AUEmqn3omynGquJR3iuJykCPWo914onfnUznT_fmz8xwbx8-yg77ncSe8UF5RCd1HWdzOGLoD_6EQf-ymNwnFP4FgsI-YIHKXThVpRJbxBV7cP8GkFUNdAJAPEX";

        System.out.println("token==="+token);
        boolean create=createMenu(token,createMenuMap(url));
        System.out.println("create==="+create);

//        sendKfMessage(token_json,"尊敬的用户，您的问题已回复\n咨询问题：考虑到卡死了可会计法缴费缴费将付款理论上看电视看多了圣诞快乐看看打卡机峰科技个\n回复内容：的历史库的缴费速度快肯定是发快递技术开发开裆裤见识到了将方式缴费","oLbL3wzpVCc_cwiiae3u6jwCnLK8");




        /**
         * {"total":7,"data":{"openid":["oLbL3w8C94NSf5fzkUCda04rnM0o","oLbL3wzpVCc_cwiiae3u6jwCnLK8","oLbL3wz0F8bEQDrMQ4wSYRT9IQhI","oLbL3wze8vCh5_K2Lo865nW6XT8s","oLbL3w-uwoTfvdChjjC9nNbKmkT8","oLbL3wwZnohcLQzjFqaCHEwrM4Kc","oLbL3w6eBeB0IYFBLGiSHrtcVsFU"]},"count":7,"next_openid":"oLbL3w6eBeB0IYFBLGiSHrtcVsFU"}
         */

//        JSONObject jsonObject = new WxPay().getBaseToken(appid,appsecret);
//        JSONObject jsonObject = new WxPay().getUsers(token);
//        JSONObject jsonObject = new WxPay().getUserDetail(token,"oLbL3w8C94NSf5fzkUCda04rnM0o");
//        JSONObject jsonObject = new WxPay().sendMessage(token,"群发测试",open_id,open_id_1);


//        JSONObject jsonObject = new WxJsUtils().sendKfMessage(token,"客服消息",open_id);
//        System.out.println(jsonObject.toJSONString());
//        System.out.println("ssss");
//
//        Map result=new WxPay().getServiceWechatPay(se_appid,se_mach_id,appid,mach_id,se_key,"测试",out_trade_no,"1","171.212.171.84","http://wxh5.nsmc.edu.cn/wx/notify/wx_notify22","oANisw1q4OHFYT6th69obAZcns2M");
//        Map result=new WxPay().getServiceQrPay(se_appid,se_mach_id,appid,mach_id,se_key,"测试",out_trade_no,"1","171.212.171.84","http://wxh5.nsmc.edu.cn/wx/notify/wx_notify22","121");


//        System.out.println("4005662001201708024010820778".length());

//        WxPay wxPay=new WxPay(appid,mach_id,"http://wxh5.nsmc.edu.cn/wx/notify/wx_notify",out_trade_no,"1",sign,"充值", "171.212.171.84","oz-vgwY4h4loCoYCmfo6gbYCf2Og");
////
//        Map map=wxPay.getWechatPay();
//        System.out.println(JSON.toJSONString(map));


        //h5
//        Map map=new WxPay().getServiceH5Pay(se_appid,se_mach_id,appid,mach_id,se_key,"测试",out_trade_no,"1","171.212.171.84","http://wxh5.nsmc.edu.cn/wx/notify/wx_notify22",Wap);







        //对账
//        String bill=new WxPay().bill(appid,"1484464372","5adc2338cca57fcf40f62963ee33b330","20170925","ALL");
//
//        FileUtils.writeByteArrayToFile(new File("/Users/lihao/Downloads/0925.csv"),bill.getBytes());
//        System.out.println(bill);
    }
}
